package com.loadmore.oneday.fragment

import android.content.Context
import android.os.Bundle
import android.view.View
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.loadmore.common.base.BaseActivity
import com.loadmore.common.base.BaseFragment
import com.loadmore.common.constants.Api
import com.loadmore.common.model.BaseResponse
import com.loadmore.common.model.Category
import com.loadmore.common.model.PageResponse
import com.loadmore.common.model.Topic
import com.loadmore.common.net.Request
import com.loadmore.common.net.impl.JsonCallback
import com.loadmore.common.permission.PermissionCallback
import com.loadmore.common.router.RouterPath
import com.loadmore.oneday.R
import com.loadmore.oneday.adapter.TopicListAdapter
import com.lzy.okgo.model.Response
import com.scwang.smartrefresh.layout.api.RefreshLayout
import kotlinx.android.synthetic.main.fragment_home.*
import java.io.Serializable


@Route(path = RouterPath.Home)
class HomeFragment : BaseFragment() {

    companion object {
        public fun newInstance(bundle: Bundle): HomeFragment {
            val homeFragment = HomeFragment()
            homeFragment.arguments = bundle
            return homeFragment
        }
    }

    var current_page = 1
    lateinit var activity: BaseActivity
    lateinit var homeListAdapter: TopicListAdapter
    override fun getLayoutId(): Int {
        return R.layout.fragment_home
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        setRefreshEnable(true)
        setLoadEnable(true)
        //actionBar.inflateMenu(R.menu.main_activity)
        //actionBar.setCenterTitle("首页")
//        actionBar.setOnMenuItemClickListener {
//            goScan()
//            return@setOnMenuItemClickListener true
//        }
        showLoading()
        getCategories()
        getHomeList(false)
        var layoutManager = androidx.recyclerview.widget.LinearLayoutManager(context)
        home_list.layoutManager = layoutManager
        home_list.isNestedScrollingEnabled = false
        homeListAdapter = TopicListAdapter(context!!)
        home_list.adapter = homeListAdapter

        cardPager.setCardClickListener {
            var bundle = Bundle()
            bundle.putString("module", RouterPath.TopicList)
            bundle.putSerializable("data", it as Serializable)
            ARouter.getInstance().build(RouterPath.Module).with(bundle).navigation()
        }
    }

    private fun getCategories() {
        Request.get(Api.category, object : JsonCallback<BaseResponse<List<Category>>>() {
            override fun onSuccess(response: Response<BaseResponse<List<Category>>>?) {
                val categories = response?.body()?.data
                cardPager.setData(categories)
                showContent()
            }

        })
    }

    private fun getHomeList(isRefresh: Boolean) {
        var params = HashMap<String, Any>()
        params.put("with_page", true)
        params.put("current_page", current_page)
        params.put("per_page", 20)
        Request.get(Api.topics, params, object : JsonCallback<BaseResponse<PageResponse<List<Topic>>>>() {
            override fun onSuccess(response: Response<BaseResponse<PageResponse<List<Topic>>>>?) {

                val body = response?.body()
                val data = body?.data
                if (isRefresh) {
                    finishRefresh()
                } else {
                    finishLoadMore()
                }
                if (body?.code == 200 && data != null) {
                    if (homeListAdapter.itemCount > 0 && current_page == 1) {
                        homeListAdapter.clearSilence()
                    }
                    val topics = data.data
                    homeListAdapter.appendSilence(topics)
                    setNoMoreData(current_page == data.last_page)
                }
            }

        })
    }

    override fun onLoadMore(refreshLayout: RefreshLayout) {
        super.onLoadMore(refreshLayout)
        current_page += 1
        getHomeList(false)
    }

    override fun onRefresh(refreshLayout: RefreshLayout) {
        super.onRefresh(refreshLayout)
        setLoadEnable(true)
        current_page = 1
        getCategories()
        getHomeList(true)
    }


    private fun goScan() {
        val permission = arrayOf(android.Manifest.permission.CAMERA)
        activity.requestPermission(permission, object : PermissionCallback {
            override fun onSettingBack() {

            }

            override fun onPermissionsDenied() {
            }

            override fun onPermissionsGranted() {
                ARouter.getInstance().build(RouterPath.QRCode).navigation()
            }

        })
    }

    override fun onAttach(context: Context?) {
        super.onAttach(context)
        activity = context as BaseActivity
    }
}